<template>
  <div ref="foodRecipeRef" class="food-recipe">
    <div class="query-item card-item">
      <span>分类：</span>
      <el-segmented v-model="foodStore.queryRecipeSegment.category"
                    :options="queryCategoryList"
                    @change="queryFoodSegmented"/>
    </div>

    <recipe-list />

    <arrive-bottom v-if="foodStore.isScrollEnd"/>
  </div>
</template>

<script lang="ts" setup>
import RecipeList from '@/components/Food/RecipeList.vue'
import ArriveBottom from '@/components/ArriveButton.vue'
import { useFoodStore } from '@/store/food.ts'
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import type { ICategory } from '@/types'

const foodRecipeRef = ref()
const foodStore = useFoodStore()

const queryCategoryList = ref([] as ICategory[])

onMounted(async () => {
  // foodStore.foodRecipeList = []
  // foodRecipeRef.value.addEventListener('scroll', handleScroll)
})

onBeforeUnmount(() => {
  // foodRecipeRef.value.removeEventListener('scroll', handleScroll)
})

watch(() => foodStore.isRefresh, () => {
  initCategoryList()
})

const initCategoryList = () => {
  queryCategoryList.value = []
  queryCategoryList.value.push({
    label: '全部',
    value: ''
  })
  foodStore.categoryList.forEach((item) => {
    queryCategoryList.value.push({
      label: item,
      value: item
    })
  })
}

const queryFoodSegmented = async () => {
  // foodStore.pageInfo.currentPage = 1
  foodStore.recipeList = []
  await foodStore.queryRecipeList()
}

const handleScroll = () => {
  const el = foodRecipeRef.value
  if (el.scrollTop + el.clientHeight >= el.scrollHeight - 10) {
    const { currentPage, pageSize, totalSize } = foodStore.pageInfo
    foodStore.isScrollEnd = pageSize * currentPage > totalSize
    if (!foodStore.isScrollEnd) {
      foodStore.pageInfo.currentPage++
      foodStore.queryRecipeList()
    }
  }
}
</script>

<style lang="scss">
.food-recipe {
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow: auto;

  .query-item {
    padding: 5px 10px;
  }
}
</style>
